package com.superpet.weixin.api.uploadFile;

import com.jfinal.kit.LogKit;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;
import com.superpet.common.controller.BaseController;
import com.superpet.common.kits.ConstantKit;
import com.superpet.weixin.api.pet.PetService;
import org.apache.commons.lang3.StringUtils;

public class UploadFileController extends BaseController {

    static UploadFileService srv = UploadFileService.me;

    public void fileUploadAction(){
        String uploadType = getPara("uploadType");
        UploadFile uploadFile = null;
        try {
            uploadFile = getFile("avatarFile", UploadFileService.uploadTempPath, UploadFileService.imageMaxSize);
            String checkMsg = srv.checkUploadFile(uploadFile);
            if (StringUtils.isNotBlank(checkMsg)) {
                renderJson(Ret.fail("code",ConstantKit.CODE_FILEUPLOAD_FAIL).set("msg", ConstantKit.MSG_FILEUPLOAD_FAIL+", "+checkMsg));
            }else{
                boolean isOk = false;
                String filePath = srv.doUploadFile(getWxSession(), uploadType, uploadFile);
                Long petPicId = 0L;
                if(StringUtils.isNotBlank(filePath)){
                    if(UploadFileService.PET_SHOW.equalsIgnoreCase(uploadType)){
                        if(getParaToLong("petId",0L)>0){
                            petPicId = PetService.me.savePetPic(getParaToLong("petId",0L),filePath);
                            isOk = true;
                        }else{
                            isOk = false;
                        }
                    }else{
                        isOk = true;
                    }
                }else{
                    isOk = false;
                }
                if(isOk){
                    renderJson(Ret.ok("code", ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS).set("filePath",filePath).set("petPicId",petPicId));
                }else{
                    renderJson(Ret.fail("code",ConstantKit.CODE_FILEUPLOAD_FAIL).set("msg", ConstantKit.MSG_FILEUPLOAD_FAIL+", FIle Upload Error"));
                }
            }
        } catch(Exception e) {
            if (uploadFile != null) {
                uploadFile.getFile().delete();
            }
            if (e.getMessage().contains("exceeds")) {
                renderJson(Ret.fail("code",ConstantKit.CODE_FILEUPLOAD_FAIL).set("msg", ConstantKit.MSG_FILEUPLOAD_FAIL+", size large than 200K"));
            } else {
                renderJson(Ret.fail("code",ConstantKit.CODE_FILEUPLOAD_FAIL).set("msg", ConstantKit.MSG_FILEUPLOAD_FAIL+", Other Error"));
                LogKit.error(e.getMessage(), e);
            }
        }
    }

}
